<?php
declare (strict_types = 1);

namespace app\services\admin\log;



use app\dao\admin\log\SystemLogDao;

use app\services\BaseServices;
use app\traits\ServicesTrait;
//use app\services\admin\setting\SystemAdminServices;
//use app\services\admin\setting\SystemMenusServices;


use support\Container;



/**
 * 系统日志
 * Class SystemLogServices
 * @package app\services\admin\log
 * @method recordAdminLog() 记录日志
 * @method deleteLog() 定期删除日志
 */
class SystemLogServices extends BaseServices
{
    use ServicesTrait;
    

    /**
     * 构造方法
     * SystemLogServices constructor.
     */
    public function __construct()
    {
        $this->dao = Container::get(SystemLogDao::class);
        //$this->dao = new SystemLogDao;
    }


    /**
     * 记录访问日志
     * @param int $adminId
     * @param string $adminName
     * @param string $type
     * @return bool
     */
    public function recordAdminLog(int $adminId, $adminName, $type)
    {
        $request = request();
        //$module = app('http')->getName();
        $route = $request->route;
        $rule = trim(strtolower($route->getPath()));

        /** @var SystemMenusServices $service */
        //$service = app()->make(SystemMenusServices::class);
        $data = [
            'method' => $request->method(),
            'admin_id' => $adminId,
            //'create_time' => time(),
            'admin_name' => $adminName,
            'path' => $rule,
            //'page' => $service->getVisitName($rule) ?: '未知',
            'ip' => $request->getRealIp(),
            'type' => $type,
            'agent' => $request->header('User-Agent'),
            'params' => json_encode($request->all()),
        ];
        if ($this->dao->save($data)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取系统日志列表
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLogList(array $where, int $level)
    {
        [$page, $limit] = $this->getPageValue();
        if (!$where['admin_id']) {
            /** @var SystemAdminServices $service */
            $service = Container::make(SystemAdminServices::class);
            $where['admin_id'] = $service->getAdminIds($level);
        }
        $list = $this->dao->getLogList($where, $page, $limit);
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }
}
